#!/bin/bash

# 项目名称，用于查找进程
APP_NAME="power-modules-patrol.jar"

# JVM参数
JAVA_OPTS="-Xms512m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError"

# 日志文件路径
LOG_FILE="./log/run.log"

# 获取应用进程ID
get_pid() {
    echo $(ps -ef | grep "$APP_NAME" | grep -v grep | awk '{print $2}')
}

# 启动应用
start() {
    PID=$(get_pid)
    if [ -n "$PID" ]; then
        echo "错误: 应用已在运行中，PID: $PID"
        exit 1
    fi
    
    echo "正在启动应用..."
    
    # 后台运行应用并将输出重定向到日志文件
    nohup java -Dfile.encoding=utf-8 $JAVA_OPTS -jar "$APP_NAME" > "$LOG_FILE" 2>&1 &
    
    echo "应用已启动"
    echo "日志文件: $(pwd)/$LOG_FILE"
}

# 关闭应用
stop() {
    PID=$(get_pid)
    if [ -z "$PID" ]; then
        echo "应用未在运行中"
        exit 0
    fi
    
    echo "正在关闭应用，PID: $PID..."
    
    # 尝试优雅关闭
    kill -15 "$PID"
    
    # 等待5秒
    for i in {1..5}; do
        PID=$(get_pid)
        if [ -z "$PID" ]; then
            echo "应用已成功关闭"
            exit 0
        fi
        echo "等待应用关闭... ($i/5)"
        sleep 1
    done
    
    # 强制关闭
    echo "尝试优雅关闭失败，正在强制关闭..."
    kill -9 "$PID"
    
    sleep 1
    PID=$(get_pid)
    if [ -z "$PID" ]; then
        echo "应用已成功关闭"
    else
        echo "关闭失败，请手动终止进程: $PID"
        exit 1
    fi
}

# 主函数
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    *)
        echo "用法: $0 [start|stop]"
        exit 1
        ;;
esac

exit 0